package com.web.common.web.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.css.sword.kernel.utils.SwordLogUtils;
import com.css.sword.platform.comm.util.StringUtils;
import com.web.common.utils.StringUtil;
import com.web.common.web.session.SwordSessionBizDataMH;

public class ValidateFilter implements Filter {
	private List<String> skipPatterns;
	private final String delim = ",";
	private static final String HTTP_PROTOCOL = "HTTP/1.1";
	private static final SwordLogUtils logger = SwordLogUtils.getLogger(ValidateFilter.class);
	private String timeoutRedirectUrl = "";
	@Override
	public void init(FilterConfig fc) throws ServletException {
		String str = fc.getInitParameter("ignore");	
		skipPatterns = Arrays.asList(StringUtils.split(str, delim));
		timeoutRedirectUrl = fc.getInitParameter("timeoutRedirectUrl");
	}
	@Override
	public void destroy() {
		
	}
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain fc) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;

		String protocol = request.getProtocol();
		if (protocol.trim().equals(HTTP_PROTOCOL)) {
			// 判断该url是否已经被禁止使用，true:不进行校验
			boolean forbided = isRequestUrlForbid(request);
			if (!forbided) {
				SwordSessionBizDataMH bizDataMH = new SwordSessionBizDataMH();
				Map<String,Object> Data = bizDataMH.getSessionAndValidate(request);
				if ("".equals(StringUtil.parse2String(Data.get("yhm")))){//session失效了 || swordData.get("jgId")==null
					String contentType = request.getHeader("Content-Type");
					if (contentType == null) {
					   redirect(request, response);
					}else{
						response.setContentType("text/json; charset=UTF-8");
						PrintWriter out = response.getWriter();
						out.println("{\"data\":[],\"message\":\"SWORD_TIME_OUT\"}");
						out.flush();
						out.close();
					}
					return;
				}
			}else{
				fc.doFilter(req, res);
			}
		}
	}


	/**
	 * 结合Sword4 验证请求的 tid 或 ctrl 是否排除在合法性校验之外
	 * 
	 * @param httpRequest
	 * @return true ：排除 false: 需要合法性校验
	 * @autor ZhangBin
	 * @since 2009-10-10
	 */
	private boolean isRequestUrlForbid(HttpServletRequest httpRequest) {
		boolean isForbided = false;
		String contentType = httpRequest.getHeader("Content-Type");
		String tid = null;
		String ctrl = null;
		if (contentType == null) {		
			String requestUrl = httpRequest.getServletPath();
			if ("/download.sword".equals(requestUrl)) {
				isForbided = true;
			}
			if ("/sword".equals(requestUrl)) {
				tid = httpRequest.getParameter("tid");
				ctrl = httpRequest.getParameter("ctrl");
				if (this.skipPatterns.contains(tid) || this.skipPatterns.contains(ctrl)) {
					isForbided = true;
				}
				logger.debug("获得请求/sword  tid:" + tid + "  ctrl:" + ctrl + "  是否拦截：" + !isForbided);
			} else {
				if (this.skipPatterns.contains(requestUrl)) {
					isForbided = true;
				}
				logger.debug("获得请求URL:" + requestUrl + "  是否拦截：" + !isForbided);
			}
		} else {
			String postData = httpRequest.getParameter("postData");
			if (postData != null) {
				isForbided = true;
				if (this.skipPatterns == null || this.skipPatterns.size() == 0) {
				} else {
					int t1 = postData.indexOf("tid");
					if (t1 > -1) {
						t1 = t1 + 4;
						t1 = postData.indexOf("\"", t1);
						if (t1 > -1) {
							t1 = t1 + 1;
							tid = postData.substring(t1, postData.indexOf("\"",t1));
						}
					}
					int t2 = postData.indexOf("ctrl");
					if (t2 > -1) {
						t2 = t2 + 5;
						t2 = postData.indexOf("\"", t2);
						if (t2 > -1) {
							t2 = t2 + 1;
							ctrl = postData.substring(t2, postData.indexOf(
									"\"", t2));
						}
					}
					if ((tid == null && ctrl == null) || 
						((tid != null || ctrl != null) && (this.skipPatterns.contains(tid) || this.skipPatterns.contains(ctrl)))) {
						isForbided = true;
					}
					logger.debug("获得请求tid:" + tid + "  ctrl:" + ctrl + "  是否拦截：" + !isForbided);
				}
			} else {
				isForbided = true;
			}
		}
		return isForbided;
	}
	
	
	/**
	 * session过期后，返回登录
	 * @param httpRequest
	 * @param httpResponse
	 * @throws IOException
	 */
	private void redirect(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException {
		PrintWriter out = httpResponse.getWriter();
		out.println("<script>");
		out.println("window.location.href='" + httpRequest.getContextPath()+ "/" + timeoutRedirectUrl + "'");
		out.println("</script>");
		out.flush();
		out.close();
	}

}
